package com.gwm.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.gwm.common.enums.ExceptionEnums;
import com.gwm.common.exceptions.LyException;
import com.gwm.upload.config.OSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class UploadService {


    // 支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg", "image/bmp");

    public String upload(MultipartFile file) {
        // 1、图片信息校验
        // 1)校验文件类型
        String type = file.getContentType();
        if (!suffixes.contains(type)) {
            throw new LyException(ExceptionEnums.INVALID_FILE_TYPE);
        }

        // 2)校验图片内容
        BufferedImage image = null;
        try {
            image = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            throw new LyException(ExceptionEnums.INVALID_FILE_TYPE);
        }
        if (image == null) {
            throw new LyException(ExceptionEnums.INVALID_FILE_TYPE);
        }

        // 2、保存图片
        // 2.1、生成保存目录,保存到nginx所在目录的html下，这样可以直接通过nginx来访问到
        File dir = new File("C:\\develop\\nginx-1.12.2\\html\\");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            // 2.2、保存图片
            file.transferTo(new File(dir, file.getOriginalFilename()));

            // 2.3、拼接图片地址
            return "http://image.gwm.com/" + file.getOriginalFilename();
        } catch (Exception e) {
            throw new LyException(ExceptionEnums.FILE_UPLOAD_ERROR);
        }
    }





    private List<String> mimeTypes = Arrays.asList("image/jpeg","image/bmp","image/png","image/gif");
    public String uploadImage(MultipartFile file){
        //        1、从扩展名上判断是否是图片
//        jpg jpeg  bmp  png gif
        if(! mimeTypes.contains( file.getContentType())){
            throw new LyException(ExceptionEnums.INVALID_FILE_TYPE);
        }
//       2、在从内容上判断是否是图片
        try {
            BufferedImage read = ImageIO.read(file.getInputStream());
            if(read==null){
                throw new LyException(ExceptionEnums.INVALID_FILE_TYPE);
            }
//        3、把图片直接先放到本地上
            file.transferTo(new File("H:\\Image\\"+file.getOriginalFilename()));
//        4、返回一个url地址  http://image.gwm.com/图片名称
            return "http://image.gwm.com/"+file.getOriginalFilename();
        } catch (IOException e) {
            throw new LyException(ExceptionEnums.INVALID_FILE_TYPE);
        }
    }


    @Autowired
    private OSS ossClient;

    @Autowired
    private OSSProperties pro;

    public Map signature() {

        try {
            long expireTime = pro.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, pro.getDir());

            String postPolicy = ossClient.generatePostPolicy(expiration,policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessId", pro.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", pro.getDir());
            respMap.put("host", pro.getHost());
            respMap.put("expire",  String.valueOf(expireEndTime));
            return respMap;
        }catch (Exception e){
            throw new LyException(ExceptionEnums.FILE_UPLOAD_ERROR);
        }
        // respMap.put("expire", formatISO8601Date(expiration));

    }
}
